import React, {Component} from 'react';
import {SafeAreaView, StyleSheet, Text, View} from 'react-native';
import Mapbox from '@mapbox/react-native-mapbox-gl';
import {Button, List, Picker} from "antd-mobile-rn";
import {Feature} from "./interface";
// import gridPattern from './grid_pattern.png';
const gridPattern = require('./grid_pattern.png');

const {Item} = List;

const {MapView, StyleURL, PointAnnotation, Callout, ShapeSource, FillLayer, VectorSource, BackgroundLayer} = Mapbox;

Mapbox.setAccessToken("pk.eyJ1IjoieHV4dXNoZW5nIiwiYSI6ImNqa2I2YXU3MTBnMDQza254MjhjMTIxaG0ifQ.bXa2dP9cO4L5tP4XlZKSHw");

const styleURLOptions = [{
    label: 'Street',
    value: StyleURL.Street
}, {
    label: "Dark",
    value: StyleURL.Dark
}, {
    label: "Light",
    value: StyleURL.Light
}];

interface Coordinates {
    accuracy: number;
    altitude: number;
    heading: number;
    latitude: number;
    longitude: number;
    speed: number;
}

interface Position {
    coords: Coordinates;
    timestamp: number;
}

interface IState {
    styleURL: string;
    isCenterLocationTracking: boolean;
    centerCoordinate?: [number, number];
    userLocation?: Position;
    annotations: number[][];
    featureCollections: {
        type: string;
        features: Feature[]
    }
}

export default class App extends Component<{}, IState> {

    state: IState = {
        styleURL: StyleURL.Street,
        isCenterLocationTracking: false,
        annotations: [],
        featureCollections: {
            type: "FeatureCollection",
            features: [{
                type: "Feature",
                properties: {},
                geometry: {
                    type: "Polygon",
                    coordinates: [[]]
                }
            }]
        }
    };

    map: any;

    componentDidMount() {
        // 正式用的话，最好提前获取下当前位置，然后设置成 center
        this.initialCenterLocation()
    }

    renderAnnotations() {
        const annotations = this.state.annotations;

        return annotations.map(a => {
            const k = a[0].toString() + a[1].toString();
            return <PointAnnotation key={k} id={k}
                                    coordinate={a}
                                    onSelected={this.onAnnotationSelected}
            >
                <View style={styles.annotationContainer}>
                    <View style={styles.annotationFill}/>
                </View>
                <Callout title={'look! an annotation'}/>
            </PointAnnotation>
        })
    }

    renderVectorSource() {
        return (
            <VectorSource>
                <BackgroundLayer id={"background"} style={layerStyles.background}/>
            </VectorSource>
        )
    }

    renderShapeSource() {
        const {annotations} = this.state;
        const shape = {
            "type": "FeatureCollection",
            "features": [
                {
                    "type": "Feature",
                    "properties": {},
                    "geometry": {
                        "type": "Polygon",
                        "coordinates": [
                            [
                                [
                                    -50.2734375,
                                    55.578344672182
                                ],
                                [
                                    -53.4375,
                                    47.989921667414
                                ],
                                [
                                    -42.5390625,
                                    47.989921667414
                                ],
                                [
                                    -41.484375,
                                    55.578344672182
                                ],
                                [
                                    -50.2734375,
                                    55.578344672182
                                ]
                            ]
                        ]
                    }
                },
                {
                    "type": "Feature",
                    "properties": {},
                    "geometry": {
                        "type": "Polygon",
                        "coordinates": [
                            [
                                [
                                    -26.71875,
                                    54.977613670696
                                ],
                                [
                                    -27.7734375,
                                    47.517200697839
                                ],
                                [
                                    -15.46875,
                                    48.458351882809
                                ],
                                [
                                    -18.6328125,
                                    54.977613670696
                                ],
                                [
                                    -26.71875,
                                    54.977613670696
                                ]
                            ]
                        ]
                    }
                },
                {
                    "type": "Feature",
                    "properties": {},
                    "geometry": {
                        "type": "Polygon",
                        "coordinates": [
                            [
                                [
                                    -52.734375,
                                    39.095962936306
                                ],
                                [
                                    -32.34375,
                                    29.840643899834
                                ],
                                [
                                    -14.0625,
                                    38.822590976177
                                ],
                                [
                                    -14.0625,
                                    30.448673679288
                                ],
                                [
                                    -32.34375,
                                    21.943045533438
                                ],
                                [
                                    -53.7890625,
                                    28.613459424004
                                ],
                                [
                                    -52.734375,
                                    39.095962936306
                                ]
                            ]
                        ]
                    }
                }
            ]
        };
        if (annotations.length > 1) {
            shape.features.push({
                type: "Feature",
                properties: {},
                geometry: {
                    type: "Polygon",
                    coordinates: [
                        annotations
                    ]
                }
            })
        }
        console.log(shape);
        return (
            <ShapeSource id={"source"} shape={shape}>
                <FillLayer id={"fill"} style={layerStyles.shapeFill}/>
            </ShapeSource>
        )
    }

    changeStyleURL = val => {
        this.setState({
            styleURL: val[0]
        })
    };

    initialCenterLocation = () => {
        navigator.geolocation.getCurrentPosition((position: Position) => {
            console.log('initial center location', position);
            this.setState({
                centerCoordinate: [position.coords.longitude, position.coords.latitude]
            })
        });
    };

    onPress = (v: Feature) => {
        console.log('press on map', v);
        let annotations = this.state.annotations;
        annotations.push(v.geometry.coordinates);
        annotations = Array.from(new Set(annotations));
        this.setState({
            annotations,
        })
    };

    onAnnotationSelected = (v) => {
        console.log('annotionSelected', v)
    };

    onUserLocationUpdate = (v: Position) => {
        console.log('userLocationUpdate: ', v);
        this.setState({
            userLocation: v
        });
        if (this.state.isCenterLocationTracking) {
            // this.map.moveTo([v.coords.longitude, v.coords.latitude])
            // todo 这里最好是根据速度和放大级别来算一下过渡时间
            this.map.flyTo([v.coords.longitude, v.coords.latitude])
        }
    };

    onRegionDidChange = v => {
        // console.log('on region did change: ', v);
        // if (!this.state.isCenterLocationTracking) {
        //   this.setState({
        //     centerCoordinate: v.geometry.coordinates
        //   })
        // }
    };

    toggleCenterLocationTracking = () => {
        const {isCenterLocationTracking} = this.state;
        if (!isCenterLocationTracking) {
            this.initialCenterLocation();
        }
        this.setState({
            isCenterLocationTracking: !isCenterLocationTracking
        })
    };

    render() {
        const {styleURL, centerCoordinate, isCenterLocationTracking} = this.state;
        return (
            <SafeAreaView style={styles.container}>
                <Text>
                    rnMapbox {new Date().toLocaleTimeString()}
                </Text>
                <View style={styles.btnWrap}>
                    <List>
                        <Picker
                            cols={1}
                            data={styleURLOptions}
                            value={[styleURL]}
                            onChange={this.changeStyleURL}
                        >
                            <Item>
                                <Text>
                                    选择主题
                                </Text>
                            </Item>
                        </Picker>
                    </List>
                    <Item>
                        <Button type={isCenterLocationTracking ? 'ghost' : 'primary'}
                                onClick={this.toggleCenterLocationTracking}>
                            {isCenterLocationTracking ? '解锁视角' : '锁定视角'}
                        </Button>
                    </Item>
                </View>
                <MapView
                    ref={ref => this.map = ref}
                    animated={true} // 地图各个设置改变的时候是否启用动画效果
                    showUserLocation={true}
                    userTrackingMode={3} // 感觉是代表当前定位的那个点的模式，为 3 时还显示方向，可选值 https://github.com/mapbox/react-native-mapbox-gl/blob/master/android/rctmgl/src/main/java/com/mapbox/rctmgl/location/UserTrackingMode.java
                    userLocationVerticalAlignment={0} // 不知道干啥的
                    // contentInset={1000}
                    pitch={100} // 感觉是俯视的角度
                    heading={10} // 方位
                    styleURL={styleURL}
                    zoomLevel={18} // 默认放大级别，值越大，视野越小
                    localizeLabels={true} // 默认将地图标签改为系统语言
                    zoomEnabled={true}
                    logoEnabled={false}
                    compassEnabled={true} // 好像是是否显示罗盘？

                    onPress={this.onPress}
                    onUserLocationUpdate={this.onUserLocationUpdate}
                    onRegionDidChange={this.onRegionDidChange}

                    centerCoordinate={centerCoordinate}
                    style={styles.mapView}>
                    {this.renderAnnotations()}
                    {this.renderVectorSource()}
                    {this.renderShapeSource()}
                </MapView>
            </SafeAreaView>

        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        borderWidth: 2,
        borderColor: "red",
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    btnWrap: {
        alignSelf: "stretch"
    },
    mapView: {
        flex: 1,
        alignSelf: "stretch"
        // height: 200,
        // width: 200
    },
    annotationContainer: {
        width: 30,
        height: 30,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: 'white',
        borderRadius: 15
    },
    annotationFill: {
        width: 30,
        height: 30,
        borderRadius: 15,
        backgroundColor: 'orange',
        transform: [{scale: 0.6}]
    },
});

const layerStyles = Mapbox.StyleSheet.create({
    background: {
        // backgroundPattern: gridPattern
    },
    shapeFill: {
        fillAntialias: true,
        fillColor: 'rgba(144,144,144,0.84)',
        fillOutlineColor: 'rgba(255,255,255,0.84)',
        backgroundPattern: gridPattern
    }
});

